<template>
	<view>
		<!-- <view  @click="oC()">打开摄像头</view> -->
		<view  @click="openCamera()">打开摄像头</view>
		<view>
		  <!-- 这里就是摄像头显示的画面 -->
		  <video id="video" width="400" height="300" autoPlay playsInline></video>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},

		methods: {
			async  oC(){
					const constraints = window.constraints ={
						audio:true,
						video:true
					}
			        try{
			            const stream = await navigator.mediaDevices.getUserMedia(constraints);
			            console.log('success');
			            this.handleSuccess(stream);
			
			        }catch(e){
			            this.handleError(e);
			        }
			    },
			
			    handleSuccess(stream){
			        const video = document.querySelector('video');
			        const videoTracks = stream.getVideoTracks();
			        console.log('使用的设备是:' + videoTracks[0].label);
			        window.stream = stream;
			        video.srcObject = stream;
			    },
			
			    handleError(error){
			        if(error.name === 'ConstraintNotSatisfiedError'){
			            const v = constraints.video;
			            message.error(`宽:${v.width.exact} 高:${v.height.exact} 设备不支持`);
			        } else if(error.name === 'PermissionDeniedError'){
			            message.error('没有摄像头和麦克风的使用权限,请点击允许按钮');
			        }
			        message.error('getUserMedia错误:',error);
			    },
			
			
			
			
			openCamera(){
				  var video = document.querySelector('video');
				  // 兼容代码
				  console.log("my is openCamera")
				  window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
				  if (navigator.mediaDevices === undefined) {
					  navigator.mediaDevices = {};
				  }
				  if (navigator.mediaDevices.getUserMedia === undefined) {
					  navigator.mediaDevices.getUserMedia = function(constraints) {
						  var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
						  if (!getUserMedia) {
							  return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
						  }
						  return new Promise(function(resolve, reject) {
							  getUserMedia.call(navigator, constraints, resolve, reject);
						  });
					  }
				  }
				  //摄像头调用配置
				  var mediaOpts = {
					  audio: true,
					  video: { facingMode: "user"} 
					  
				  }
	 
				  let that=this;
				  navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
					  that.mediaStreamTrack = stream;
					  video = document.querySelector('video');
					  if ("srcObject" in video) {
						  video.srcObject = stream
					  } else {
						  video.src = window.URL && window.URL.createObjectURL(stream) || stream
					  }
					  video.play();
				  }).catch(function (err) {
					  console.log(err)
				  });
			}
		}
	}
</script>

<style>

</style>
